#!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ == taoyulong2018@gmail.com
# __time__ == 2023/8/16 17:25
# ===========================================
#       题目名称： 2. 两数相加
#       题目地址： https://leetcode.cn/problems/add-two-numbers/
#       题目描述： https://note.youdao.com/s/RRXNSXjR
# ===========================================

from utils import *


# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    """
        实现逻辑：
            递归
    """

    def addTwoNumbers(self, l1, l2):
        result = None
        if not (l1 or l2):  # 如果两个都为空
            return result
        l1_val, l2_val = 0, 0  # l1 l2
        if l1:
            l1_val = l1.val
        if l2:
            l2_val = l2.val
        val = l1_val + l2_val
        l1_next, l2_next = None, None  # l1 l2 下一个值
        if l1 and l1.next:
            l1_next = l1.next
        if l2 and l2.next:
            l2_next = l2.next
        if val >= 10:
            if l1_next:
                l1_next.val += 1
            elif l2_next:
                l2_next.val += 1
            else:
                l1_next = ListNode(1)
            val -= 10
        result = ListNode(val, self.addTwoNumbers(l1_next, l2_next))
        return result


if __name__ == '__main__':
    s = Solution()
    print("[7,0,8] =>", StringUtils.to_string(s.addTwoNumbers(
        l1=ListNode(2, ListNode(4, ListNode(3))),
        l2=ListNode(5, ListNode(6, ListNode(4))))))
    print("[0] =>", StringUtils.to_string(s.addTwoNumbers(
        l1=ListNode(0),
        l2=ListNode(0))))
    print("[8,9,9,9,0,0,0,1] =>", StringUtils.to_string(s.addTwoNumbers(
        l1=ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9, ListNode(9))))))),
        l2=ListNode(9, ListNode(9, ListNode(9, ListNode(9)))))))
